import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
    Alert,
    Clipboard,
    Modal
} from 'react-native';

import AndroidModule from 'src/utils/AndroidConnent'
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Header from "../../components/header";
import { ToastToUser } from '../../utils/CustomToast';
import Loading from "../../utils/Loading";
import NoData from "../../utils/NoData";
import { getImgUrl } from '../../utils/ComFunction'
import ActionSheet from 'react-native-actionsheet'
import moment from 'moment';
import { shareWebToSession, shareWebToTimeline } from '../../utils/WeChatUtils'

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

const colorsOptions = ['#ED542E', '#2CE454', '#2CE454', '#ff6600', '#ED542E']

let navigation

export default class ContractListPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            contractCount: 0,//剩余条数
            searchKey: '',//搜索关键字
            isInitiatorSign: '',//发起人是否已签

            //合同类型选择相关
            contractTypeOptions: ['平台交易', '销售', '收购', '其他', '取消'],
            contractTypeOptionsValue: [0, 1, 2, 3],
            contractType: '',
            contractTypeTitle: '',

            //合同状态选择相关
            contractStatusOptions: [ '签署中', '完成签署', '已废弃', '已过期', '已拒签', '解约中', '部分已解约', '已解约',  '取消'],
            contractStatusOptionsValue: [ 1, 2, 3, 5, 7, 10, 11, 12, ''],
            contractStatus: '',
            contractStatusTitle: '',

            isWaitSign: false,//待我方签署

            chooseType: false,//选择发起合同

            contractLists: [],

            rescissionShow: false,
            rescindReason: '',
            rescindReasonKey: '',
            rescindReasonArr: ['条款内容有误', '印章选择错误', '签署人信息错误', '合作终止', '其他', '取消'],
            rescindReasonArrKey: [1, 2, 3, 4, 5, -1],
            rescindReasonNotes: '',
            chooseSissionItem: [],

            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,

            //选择签署方
            showAssigns: false,
            assigns: [],
            chooseSendItem: [],

            //废弃合同
            chooseDiscard: [],
            discardReasonArr: ['直接废弃', '废弃并重新发起', '取消'],
            chooseDiscardIndex: 0,
            showDiscard: false
        }
    }

    componentWillMount() {
        this.commonEventLinster = DeviceEventEmitter.addListener('commonEvent', e => {
            if (e.eventName == 'contractPaySuccess') {
                this.getCount()
            }
        });
    }

    componentWillUnmount() {
        this.commonEventLinster.remove();
    }


    renderRightButton() {
        return (
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={()=>{
                    navigation.navigate('SignSettingsPage')
                }}>
                <View style={styles.rightBox}>
                    <Text style={styles.rightText}>管理</Text>
                </View>
            </TouchableOpacity>
        )
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'电子合同'} righBtnTtitle={'管理'} RightButton={()=>this.renderRightButton()}/>
                {/* 合同剩余条数 */}
                {/* <View style={styles.contractCountContainer}>
                    <Text style={styles.contractCount}>合同剩余: {this.state.contractCount}份</Text>
                    <TouchableOpacity
                        activeOpacity={0.8}
                        style={styles.chargeContainer}
                        onPress={this.gotocharge.bind(this)}>
                        <View >
                            <Text style={styles.chargeTitle}>充值</Text>
                        </View>
                    </TouchableOpacity>
                </View> */}
                {/* 搜索框 */}
                <View style={styles.searchContainer}>
                    <View style={styles.searchLayout}>
                        <Image source={require('source/image/electron/search.png')} style={styles.sarchIcon} />
                        <TextInput
                            editable={true}
                            style={styles.inputbox}
                            placeholder='合同名称/车辆名称/车架号'
                            placeholderTextColor={'#999999'}
                            maxLength={17}
                            value={this.state.searchKey}
                            onChangeText={this.onChangeTextHandle}
                            onEndEditing={this.handleKeyboardFinish.bind(this)}
                        ></TextInput>
                        {
                            this.state.searchKey
                                ?
                                <TouchableOpacity
                                    activeOpacity={0.8}
                                    style={{ position: 'absolute', right: 15 }}
                                    onPress={this.clearSearch.bind(this)}>
                                    <Image source={require('source/image/electron/searchClose.png')} style={styles.sarchClose} />
                                </TouchableOpacity>
                                :
                                null
                        }

                    </View>
                </View>

                {/* 选择栏 */}
                <View style={styles.chooseContainer}>
                    {/* 合同类型 */}
                    <TouchableOpacity
                        style={styles.choosePer}
                        activeOpacity={0.8}
                        onPress={this.chooseTypeSearch.bind(this)}
                    >
                        <View style={styles.choosePerinner}>
                            <Text style={styles.choosetype}>{this.state.contractTypeTitle ? this.state.contractTypeTitle : '合同类型'}</Text>
                            <Image source={require('source/image/electron/choosearrow.png')} style={styles.choosearrow} />
                        </View>
                    </TouchableOpacity>
                    {/* 合同状态 */}
                    <TouchableOpacity
                        style={styles.choosePer}
                        activeOpacity={0.8}
                        onPress={this.chooseStatusSearch.bind(this)}
                    >
                        <View style={styles.choosePerinner}>
                            <Text style={styles.choosetype}>{this.state.contractStatusTitle ? this.state.contractStatusTitle : '合同状态'}</Text>
                            <Image source={require('source/image/electron/choosearrow.png')} style={styles.choosearrow} />
                        </View>
                    </TouchableOpacity>
                    {/* 待我方签署 */}
                    <TouchableOpacity
                        style={styles.choosePer}
                        activeOpacity={0.8}
                        onPress={this.chooseWaitSign.bind(this)}
                    >
                        <View style={styles.choosePerinner}>
                            {
                                this.state.isWaitSign
                                    ?
                                    <Image source={require('source/image/electron/choosesignselect.png')} style={styles.choosesign} />
                                    :
                                    <Image source={require('source/image/electron/choosesign.png')} style={styles.choosesign} />
                            }
                            <Text style={this.state.isWaitSign ? styles.choosetypeSelect : styles.choosetype}>待我方签署</Text>
                        </View>
                    </TouchableOpacity>

                </View>

                {/* 合同列表数据 */}
                {this.renderList()}

                {/* 底部添加合同按钮 */}
                {/* <TouchableOpacity
                    style={[styles.addcontractContainer, { bottom: Constant.isIPhoneX ? Constant.bottomHeight + 45 : 45, right: 15, position: 'absolute' }]}
                    activeOpacity={0.8}
                    onPress={this.startContract.bind(this)}>
                    <Image source={require('source/image/electron/contractadd.png')} style={styles.contractadd} />
                    <Text style={styles.addcontractTitle}>发起合同</Text>
                </TouchableOpacity> */}

                {/* 选择合同类型 */}
                {
                    this.state.chooseType
                        ?
                        <TouchableOpacity
                            style={styles.chooseTypeContaner}
                            activeOpacity={1}
                            onPress={this.chooseTypeClose.bind(this)}
                        >
                            <View
                                style={styles.chooseTypeBottoms}
                            >
                                <View style={styles.chooseTypeTop}>
                                    <Text style={styles.choosetypetitle}>请选择合同类型</Text>
                                    <TouchableOpacity
                                        activeOpacity={0.8}
                                        style={styles.chooseclose}
                                        onPress={this.chooseTypeClose.bind(this)}>
                                        <Image source={require('source/image/electron/chooseclose.png')} style={{ width: 15, height: 15 }} />
                                    </TouchableOpacity>
                                </View>
                                <View style={styles.chooseCenterContainer}>
                                    {/* 采购合同 */}
                                    <TouchableOpacity
                                        onPress={this.chooseTypeSelect.bind(this, '2')}
                                    >
                                        <View style={styles.funcontainer}>
                                            <Image source={require('source/image/electron/contractpurchse.png')} style={styles.contractTypeIcon} />
                                            <Text style={styles.cobtractTypeTitle}>采购合同</Text>
                                        </View>
                                    </TouchableOpacity>
                                    {/* 销售合同 */}
                                    <TouchableOpacity
                                        onPress={this.chooseTypeSelect.bind(this, '1')}
                                    >
                                        <View style={styles.funcontainer}>
                                            <Image source={require('source/image/electron/contracticon.png')} style={styles.contractTypeIcon} />
                                            <Text style={styles.cobtractTypeTitle}>销售合同</Text>
                                        </View>
                                    </TouchableOpacity>
                                    {/* 其他 */}
                                    <TouchableOpacity
                                        onPress={this.chooseTypeSelect.bind(this, '3')}
                                    >
                                        <View style={styles.funcontainer}>
                                            <Image source={require('source/image/electron/contractother.png')} style={styles.contractTypeIcon} />
                                            <Text style={styles.cobtractTypeTitle}>其他</Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </TouchableOpacity>
                        :
                        null
                }

                {/* 筛选合同类型 */}
                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    options={this.state.contractTypeOptions}
                    cancelButtonIndex={this.state.contractTypeOptions.length - 1}
                    onPress={(index) => { this.selectContractTypeOption(index) }}
                />

                {/* 筛选合同状态 */}
                <ActionSheet
                    ref={o => this.ActionSheetStatus = o}
                    options={this.state.contractStatusOptions}
                    cancelButtonIndex={this.state.contractStatusOptions.length - 1}
                    onPress={(index) => { this.selectContractStatusOption(index) }}
                />

                {/* 筛选解约原因 */}
                <ActionSheet
                    ref={o => this.ActionSheetScission = o}
                    options={this.state.rescindReasonArr}
                    cancelButtonIndex={this.state.rescindReasonArr.length - 1}
                    onPress={(index) => { this.selectContractRescissOption(index) }}
                />

                {/* 解约弹框 */}
                {
                    this.state.rescissionShow
                        ?
                        <TouchableOpacity
                            style={styles.chooseTypeContaner}
                            activeOpacity={0.8}
                            onPress={this.chooseTypeClose.bind(this)}
                        >
                            <View
                                style={[styles.rescissionTypeContaner, { bottom: Constant.isIPhoneX ? Constant.bottomHeight : 0 }]}
                            >
                                <View style={styles.chooseTypeTop}>
                                    <Text style={styles.choosetypetitle}>解约页面</Text>
                                    <TouchableOpacity
                                        activeOpacity={0.8}
                                        style={styles.chooseclose}
                                        onPress={this.chooseTypeClose.bind(this)}>
                                        <Image source={require('source/image/electron/chooseclose.png')} style={{ width: 15, height: 15 }} />
                                    </TouchableOpacity>
                                </View>
                                <TouchableOpacity
                                    activeOpacity={0.8}
                                    onPress={this.chooseRescission.bind(this)}
                                >
                                    <View style={styles.rescissionContainer}>
                                        <Text style={{ marginLeft: 15, color: '#666666' }}>解约原因
                                            <Text style={{ color: 'red' }}>*</Text>
                                        </Text>
                                        <Text style={{ marginRight: 15, color: '#333333', textAlign: 'right', flex: 1 }}>{this.state.rescindReason ? this.state.rescindReason : '请先选择解约原因'}</Text>

                                    </View>
                                </TouchableOpacity>



                                <View
                                    style={{ height: 70, width: screenW - 60, backgroundColor: '#ffffff', borderColor: '#e1e1e1', borderWidth: 1, marginLeft: 30, marginTop: 10 }}
                                >
                                    <TextInput
                                        style={{
                                            height: 70,
                                            width: screenW - 30,
                                            marginLeft: 12,
                                            marginRight: 12,
                                            lineHeight: 20
                                        }}
                                        onChangeText={this.onChangeRescission}
                                        placeholder='请具体输入解约原因'
                                        placeholderTextColor={'#999999'}
                                        numberOfLines={3}
                                        multiline={true}
                                        textAlignVertical="top"
                                    ></TextInput>
                                </View>
                                <TouchableOpacity
                                    activeOpacity={0.8}
                                    onPress={this.scissionSubmite.bind(this)}
                                >
                                    <View style={{ height: 40, width: screenW - 60, marginLeft: 30, alignItems: 'center', justifyContent: 'center', backgroundColor: '#FFEF3A', marginTop: 15 }}>
                                        <Text>确认提交</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>

                        </TouchableOpacity>
                        :
                        null
                }


                {/* 选择签署方 */}
                {
                    this.state.showAssigns
                        ?
                        <View style={styles.containerAssign}>
                            <TouchableOpacity
                                style={styles.closeContainer}
                                activeOpacity={0.8}
                                onPress={this.closeContainer.bind(this)}
                            >
                                <View></View>

                            </TouchableOpacity>

                            <View style={[styles.modalContainer, {}]}>
                                <View style={[styles.assignItem]}>
                                    <Text style={{ color: '#333333', fontSize: 16, fontWeight: '500' }}>请先选择要发送的签署方</Text>
                                    <View style={styles.borderBottom} >
                                    </View>
                                </View>

                                {this.state.assigns.map(item => (
                                    <TouchableOpacity
                                        key={item}
                                        style={[styles.assignItem]}
                                        onPress={this.choosesignsItem.bind(this, item)}
                                    >
                                        <Text style={styles.itemText}>{item}</Text>

                                        <View style={styles.borderBottom} >
                                        </View>
                                    </TouchableOpacity>
                                ))}

                                {
                                    isIPhoneX ?
                                        <View style={{ width: '100%', height: 34, backgroundColor: '#FFF' }} />
                                        :
                                        null
                                }

                            </View>

                        </View>
                        :
                        null
                }

                {/* 筛选废弃合同 */}
                <ActionSheet
                    ref={o => this.ActionSheetDiscard = o}
                    options={this.state.discardReasonArr}
                    cancelButtonIndex={this.state.discardReasonArr.length - 1}
                    onPress={(index) => { this.selectContractDiscardOption(index) }}
                />

                {/* 选择废弃合同的弹框提醒 */}
                {
                    this.state.showDiscard
                        ?
                        <View style={styles.chooseTypeContaner}>

                            <View style={styles.commondialog}>
                                <Text style={{ marginTop: 25, fontSize: 15, color: '#333333', fontWeight: '400' }}>您确定废弃掉目前正在签署中的合同吗？</Text>
                                <TouchableOpacity
                                    onPress={this.revoke.bind(this, this.state.chooseDiscard)}
                                >
                                    <View style={{ width: screenW - 80, height: 43, alignItems: 'center', justifyContent: 'center', marginTop: 35, backgroundColor: '#FFE000', borderRadius: 5 }}>
                                        <Text style={{ fontSize: 15, color: '#333333', fontWeight: '600' }}>确认</Text>
                                    </View>
                                </TouchableOpacity>

                                <TouchableOpacity
                                    onPress={this.closeShowDiscard.bind(this)}
                                >
                                    <View style={{ width: screenW - 80, height: 43, alignItems: 'center', justifyContent: 'center', marginTop: 15, backgroundColor: '#ffffff', borderRadius: 5, marginBottom: 20 }}>
                                        <Text style={{ fontSize: 15, color: '#666666', fontWeight: '400' }}>取消</Text>
                                    </View>
                                </TouchableOpacity>

                            </View>
                        </View>
                        :
                        null
                }


                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        )
    }




    componentDidMount() {
        this.refreshData()
    }

    //输入解约原因
    onChangeRescission = (value) => {
        this.setState({ rescindReasonNotes: value });
    }

    //选择解约原因
    chooseRescission() {
        if (this.ActionSheetScission) {
            this.ActionSheetScission.show()
        }
    }

    //解约提交
    scissionSubmite() {
        if (!this.state.rescindReasonKey) {
            ToastToUser('请先选择解约原因')
            return
        }

        if (this.Loading) {
            this.Loading.show();
        }

        let param = {
            contractNo: this.state.chooseSissionItem.contractNo,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
            operator: Constant.userInfo.fullname ? Constant.userInfo.fullname : Constant.userInfo.userId,
            rescindReason: this.state.rescindReasonKey,
            rescindReasonNotes: this.state.rescindReasonNotes
        }

        // console.log(param)
        HttpUtils.postRequest(HttpUrls.rescission, param)
            .then((result) => {
                console.log(result)
                if (this.Loading) {
                    this.Loading.hide();
                }
                let code = result.code
                if (code == 0) {
                    this.chooseTypeClose()
                    this.refreshData()
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {

            });
    }

    //充值
    gotocharge() {
        navigation.navigate('ContractRechargePage')
    }

    //关键字输入信息变化
    onChangeTextHandle = (value) => {
        this.setState({ searchKey: value });
    }

    //清除搜索关键词
    clearSearch() {
        this.setState(
            {
                searchKey: ''
            }, function () {
                this.refreshData()
            });
    }

    //关键字搜索完成输入直接搜索
    handleKeyboardFinish() {
        this.refreshData()
    }

    //筛选合同类型
    chooseTypeSearch() {
        if (this.ActionSheet) {
            this.ActionSheet.show()
        }
    }

    //选择合同类型
    selectContractTypeOption(index) {
        if (index != this.state.contractTypeOptions.length - 1) {
            this.setState({
                contractType: this.state.contractTypeOptionsValue[index],
                contractTypeTitle: this.state.contractTypeOptions[index]
            }, function () {
                this.refreshData()
            })
        }
    }

    //选择合同状态
    chooseStatusSearch() {
        if (this.ActionSheetStatus) {
            this.ActionSheetStatus.show()
        }
    }

    //选择合同状态
    selectContractStatusOption(index) {
        if (index != this.state.contractStatusOptions.length - 1) {
            this.setState({
                contractStatus: this.state.contractStatusOptionsValue[index],
                contractStatusTitle: this.state.contractStatusOptions[index],
            }, function () {
                this.refreshData()
            })
        }
    }

    //选择解约原因
    selectContractRescissOption(index) {
        if (index != this.state.rescindReasonArr.length - 1) {
            this.setState({
                rescindReason: this.state.rescindReasonArr[index],
                rescindReasonKey: this.state.rescindReasonArrKey[index],
            }, function () {

            })
        }
    }

    //选择待我方签署
    chooseWaitSign() {
        let temp = this.state.isWaitSign
        this.setState({
            isWaitSign: !temp,
            isInitiatorSign: !temp ? '0' : ''
        }, function () {
            this.refreshData()
        })
    }

    //发起合同
    startContract() {
        if(this.state.contractCount == 0){
            ToastToUser('当前合同余额不足，请先充值')
            return
        }

        this.setState({
            chooseType: true
        })
    }

    //选择合同类型
    chooseTypeSelect(type) {
        this.setState({
            chooseType: false
        })
        navigation.navigate('ChooseTemplatePage', {chooseType: type})
    }

    chooseTypeClose() {
        this.setState({
            chooseType: false,
            rescissionShow: false,
        })
    }

    renderList() {
        return (
            <View style={{ flex: 1, marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0 }}>
                <FlatList
                    data={this.state.contractLists}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.3}
                />

            </View>
        )
    }

    renderItemView({ item, index }) {
        // const containsThree = item.contractSignersInfo.includes(3);
        // let allOnes = item.contractSignersInfo.every(contractSignersInfo => contractSignersInfo.signStatus === 2);
        let allOnes=item.contractStatus === 1


        return (
            <TouchableOpacity key={item.contractNo}
                onPress={() => { 
                    navigation.navigate('ContractDetailPage', { contractNo: item.contractNo })
                 }}>
                {/* 列表数据 */}
                <View style={styles.itemcontainer}>
                    <View style={styles.itemtop}>
                        <Text style={styles.contractNameTitle} >电子合同-销售 </Text>
                        <Text style={styles.contractName} numberOfLines={1} ellipsizeMode={'tail'} >{item.contractNo}</Text>
                        {
                            allOnes
                                ?
                                <Text style={styles.contractStatus}>{item.isInitiatorSign == 0 ? '待我方签署' : '待他方签署'}</Text>
                                :
                                <Text style={[styles.contractStatusComplete,{color: item.contractStatus ==2?'#2CE454': '#ED542E'}]}>{this.getrightshow(item.contractStatus)}</Text>
                        }

                    </View>
                    <Text style={styles.contractModel}>{item.contractName ? item.contractName : "未填写合同名称"}</Text>
                    <View style={styles.commonbuttwen}>
                        <Text style={styles.commonTitle}>发起：</Text>
                        <Text style={styles.commonValue}>{item.initiatorUserName} ({item.initiatorMerchantName})</Text>
                    </View>
                    <View style={styles.commonbuttwen}>
                        <Text style={styles.commonTitle}>时间：</Text>
                        <Text style={styles.commonValue}>{this.getcreateTime(item.initiatorTime)}</Text>
                    </View>

                    {
                        item.contractSignersInfo.length > 0 ?
                            <View style={[styles.commonbuttwen, { flexWrap: 'wrap', flex: 1, marginEnd: 10 }]}>
                                {
                                    this.getStatusList(item.contractSignersInfo).map((itemInfo, index) => {
                                        let colorStatus = colorsOptions[itemInfo.signStatus]
                                        return (
                                            <View style={{ flexDirection: 'row', marginRight: 10, alignItems: 'center' }}>
                                                <Text style={[styles.commonTitle, { color: colorStatus }]}>{this.getStatusTitle(itemInfo.signStatus)}:</Text>
                                                <Text style={styles.commonValue}>{itemInfo.title}</Text>
                                            </View>
                                        )
                                    })


                                }

                            </View>
                            :
                            null
                    }

                    {/* 车辆相关 */}
                    {
                        item.bizInfo && JSON.parse(item.bizInfo).carName
                            ?
                            <View style={styles.contractCarContainer}>
                                {
                                    JSON.parse(item.bizInfo).mainPic
                                        ?
                                        <Image style={styles.contractcar}
                                            source={{ uri: getImgUrl(JSON.parse(item.bizInfo).mainPic) }}></Image>
                                        :
                                        <Image source={require('source/image/electron/carpic.png')} style={styles.contractcar} />
                                }

                                <View>
                                    <Text style={styles.contractCarTitle} numberOfLines={1}>{JSON.parse(item.bizInfo).carName.replaceAll('#',' ')}</Text>
                                    <Text style={styles.contractCarVin}>{JSON.parse(item.bizInfo).vcode ? ('VIN:' + JSON.parse(item.bizInfo).vcode.toUpperCase()) : ''}</Text>
                                </View>
                            </View>
                            :
                            null
                    }
                    {/* 底部按钮 */}
                    <View style={styles.itemBottomContainer}>
                        {this.getBottomView(item)}
                    </View>

                </View>
            </TouchableOpacity>
        )
    }



    getrightshow(temp){
        if(temp == 2){
            return '完成签署'
        }else if(temp == 3){
            return '已废弃'
        }else if(temp == 5){
            return '已过期'
        }else if(temp == 7){
            return '已拒签'
        }else if(temp == 10){
            return '解约中'
        }else if(temp == 11){
            return '部分已解约'
        }else if(temp == 12){
            return '已解约'
        }else{
             return ''
        }
    }

    getStatusList(temp) {
        const result = [];
        const statusMap = {};
        temp.forEach(item => {
            const transactorName = item.psnName || item.transactorName
            const { signStatus } = item;

            // 如果状态已经存在于 statusMap 中，则追加名称
            if (statusMap[signStatus]) {
                statusMap[signStatus].push(transactorName);
            } else {
                // 否则，创建新的状态条目
                statusMap[signStatus] = [transactorName];
            }
        });

        for (const [signStatus, names] of Object.entries(statusMap)) {
            result.push({
                signStatus: signStatus,
                title: names.join(',') // 将名称数组转换为字符串
            });
        }

        return result

    }

    getBottomView(item) {


        let containsThree = item.contractSignersInfo.some(contractSignersInfo => contractSignersInfo.signStatus === 4);
        let allOnes = item.contractSignersInfo.every(contractSignersInfo => contractSignersInfo.signStatus === 2);

        if (item.contractStatus == 2) {
            allOnes = true
        }

        if (containsThree) {
            return (

                <View style={styles.itemBottomLayout}>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={this.reviewStart.bind(this, item)}
                    >
                        <View style={styles.commonbtn}>
                            <Text style={styles.commonBtnTitle}>重新发起</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            )
        } else if (allOnes) {
            return (
                <View style={styles.itemBottomLayout}>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={() => {
                            navigation.navigate('ContractDetailPage', { contractNo: item.contractNo })
                        }}
                    >
                        <View style={styles.commonbtn}>
                            <Text style={styles.commonBtnTitle}>查看</Text>
                        </View>
                    </TouchableOpacity>
                    {
                        (item.contractStatus !=10 && item.contractStatus !=11 && item.contractStatus !=12)
                        ?
                        <TouchableOpacity
                        activeOpacity={1}
                        onPress={this.rescission.bind(this, item)}
                    >
                        <View style={styles.commonbtn}>
                            <Text style={styles.commonBtnTitle}>解约</Text>
                        </View>
                    </TouchableOpacity>
                        :
                        null
                    }
                  
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={this.downloadContract.bind(this, item)}>
                        <View style={styles.commonbtn}
                           

                        >
                            <Text style={styles.commonBtnTitle}>下载</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            )
        } else {
            return (
                <View style={styles.itemBottomLayout}>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={this.checkContract.bind(this, item)}
                    >
                        <View style={styles.commonbtn}>
                            <Text style={styles.commonBtnTitle}>查看</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={this.discardContract.bind(this, item)}
                    >
                        <View style={styles.commonbtn}>
                            <Text style={styles.commonBtnTitle}>废弃合同</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={this.getSignUrl.bind(this, item)}
                    >
                        <View style={styles.commonbtn}>
                            <Text style={styles.commonBtnTitle}>发送填写链接</Text>
                        </View>
                    </TouchableOpacity>
                </View>

            )
        }


    }

    getcreateTime(time) {
        return moment(time).format("YYYY-MM-DD HH:mm")
    }

    //通过状态获取标题
    getStatusTitle(status) {
        if (status == 0) {
            return '待签'
        } else if (status == 1) {
            return '签署中'
        } else if (status == 2) {
            return '已签'
        } else if (status == 3) {
            return '等待审批'
        } else if (status == 4) {
            return '已拒签'
        }
    }

    renderEmpty() {
        return (
            <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
        )
    }


    //解约合同
    rescission(item) {
        this.setState({
            rescissionShow: true,
            rescindReason: '',
            rescindReasonKey: '',
            rescindReasonNotes: '',
            chooseSissionItem: item
        })
    }

    //下载合同
    downloadContract(item) {

        if (this.Loading) {
            this.Loading.show();
        }

        let param = {
            contractNo: item.contractNo,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
        }

        HttpUtils.getRequest(HttpUrls.downloadPdf, param)
            .then((result) => {

                if (this.Loading) {
                    this.Loading.hide();
                }


                let code = result.code

                if (code == 0) {
                    let times = item.contractNo+new Date().getTime() 
                    let fileName = item.contractName+'_'+times+ '.pdf'
                    AndroidModule.downloadContract({downloadUrl:result.data,isShare:true,fileName:fileName})
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {

            });

    }

    // 点击查看合同
    checkContract(item) {
       
        if (this.Loading) {
            this.Loading.show();
        }

        let param = {
            contractNo: item.contractNo,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
        }

        HttpUtils.getRequest(HttpUrls.downloadPdf, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }

                let code = result.code
                console.log('=========>>>>>>>>>>>>>2')

                if (code == 0) {
                    let obj = {
                        fileDownloadUrl: result.data,
                        typepage: '1040',
                        templateId: '-1'
                    }

                    Linking.openURL(result.data).catch(err => console.error('An error occurred', err));

                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {

            });

    }

    //废弃合同
    discardContract(item) {


        this.setState({
            chooseDiscard: item
        })
        if (this.ActionSheetDiscard) {
            this.ActionSheetDiscard.show()
        }


    }

    closeShowDiscard() {
        this.setState({
            showDiscard: false
        })
    }

    selectContractDiscardOption(index) {
        if (index != this.state.discardReasonArr.length - 1) {


            this.setState({
                chooseDiscardIndex: index,
                showDiscard: true
            }, function () {
                // this.revoke(this.state.chooseDiscard)

                //              Alert.alert(
                //     '废弃合同',
                //     '您确定废弃掉目前正在签署中的合同吗？',
                //     [
                //         { text: '取消', onPress: () => { } },
                //         {
                //             text: '确认', onPress: () => {
                //                 this.revoke(this.state.chooseDiscard)
                //             }
                //         },
                //     ]
                // )
            })
        }
    }
    //废弃
    revoke(item) {
        if (this.Loading) {
            this.Loading.show();
        }

        let param = {
            contractNo: item.contractNo,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
            revokeReason: '',
            operator: Constant.userInfo.fullname ? Constant.userInfo.fullname : Constant.userInfo.userId,
        }
        HttpUtils.postRequest(HttpUrls.revoke, param)
            .then((result) => {
                console.log(result)
                if (this.Loading) {
                    this.Loading.hide();
                }
                let code = result.code
                if (code == 0) {
                    this.setState({
                        showDiscard: false
                    })
                    this.refreshData()
                    if (this.state.chooseDiscardIndex == 1) {
                        //重新发起
                        // console.log(item.templateId)
                        this.reviewStart(item)

                    }
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {

            });
    }

    closeContainer() {
        this.setState({
            showAssigns: false,
        })
    }

    //选择的签署方
    choosesignsItem(itemTitle) {
        if (this.Loading) {
            this.Loading.show();
        }
        let psnAccount = ''
        let orgName = ''
        let selectItem = null
        for (let i = 0; i < this.state.chooseSendItem.contractSignersInfo.length; i++) {
            if (this.state.chooseSendItem.contractSignersInfo[i].participantFlag == itemTitle) {
                // if (this.state.chooseSendItem.contractSignersInfo[i].orgName) {
                //     orgName = this.state.chooseSendItem.contractSignersInfo[i].orgName
                // } else {
                //     psnAccount = this.state.chooseSendItem.contractSignersInfo[i].psnAccount
                // }
                selectItem = this.state.chooseSendItem.contractSignersInfo[i]

                break
            }
        }

        console.log('selectItem',selectItem)

        let param = {
            contractNo: this.state.chooseSendItem.contractNo,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,

        }

        if (selectItem.participantType == 1) {//企业
            param.transactorPsnAccount = selectItem.transactorPsnAccount
            
        }else{
            param.psnAccount = selectItem.psnAccount
        }



        // if (psnAccount) {
        //     param.psnAccount = psnAccount
        // } else {
        //     param.orgName = orgName
        // }

        HttpUtils.postRequest(HttpUrls.getSignUrl, param)
            .then((result) => {
                console.log(result)
                if (this.Loading) {
                    this.Loading.hide();
                }
                let code = result.code
                if (code == 0) {
                    //  Clipboard.setString(result.data);
                    // ToastToUser('已复制到剪切板')
                    this.setState({
                        showAssigns: false
                    })

                    // let shareObj = {
                    //     shareTitle: '您有一份合同待签署',
                    //     shareContent: this.state.chooseSendItem.initiatorMerchantName + '给您发送了合同《' + this.state.chooseSendItem.templateName + '》，请您签署',
                    //     shareUrl: result.data,
                    //     shareImage: 'https://img.shuaiche.com/img/statics/app/contract/icon_pdf.png'
                    // }

                    let shareObj = {
                        title: '您有一份合同待签署',
                        description: this.state.chooseSendItem.initiatorMerchantName + '给您发送了合同《' + this.state.chooseSendItem.templateName + '》，请您签署',
                        type: 'news',
                        webpageUrl: result.data,
                        thumbImage: 'https://img.shuaiche.com/img/statics/app/contract/icon_pdf.png'
                    }

                    // console.log(shareObj)
                    try {
                        shareWebToSession(shareObj)
                        // AndroidModule.share(shareObj)
                    } catch (error) {
                        
                    }

                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {

            });

    }



    //获取填写链接
    getSignUrl(item) {

        let temp = []

        for (let i = 0; i < item.contractSignersInfo.length; i++) {

            temp.push(item.contractSignersInfo[i].participantFlag)
        }

        this.setState({
            showAssigns: true,
            assigns: temp,
            chooseSendItem: item
        })



    }

    //重新发起
    reviewStart(item) {
        // navigation.navigate('SignatoryPage', {templateId: item.templateId+'',})
        navigation.navigate('SignMainBodyPage', { orderNo: item.bizId })
    }

    //刷新数据
    refreshData = () => {
        this.getCount()
        this.setState({
            isRefresh: true,
            pageNo: 1,
            contractLists: []
        }, function () {
            this.getContracts()
        })
    }

    //获取数量
    getCount() {
        let param = {
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
        }

        HttpUtils.getRequest(HttpUrls.getByMerchantId, param)
            .then((result) => {

                this.setState({
                    contractCount: result.data.contractAvalable
                })

            })
            .catch((error) => {

            });
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;

        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }
        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1
            }, function () {
                this.getContracts()
            });
    }


    getContracts() {
        let param = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            initiatorMerchantId: Constant.userInfo.merchantId,
            userId: Constant.userInfo.userId,
            keyWord: this.state.searchKey,
            contractType: this.state.contractType,
            contractStatus: this.state.contractStatus,
            isInitiatorSign: this.state.isInitiatorSign
        }

        HttpUtils.postRequest(HttpUrls.contractProdmerchantSearchList, param)
            .then((result) => {
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    if (resultList && resultList != null && resultList.length > 0) {
                        this.setState({
                            contractLists: this.state.contractLists.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            })
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }


}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        backgroundColor: '#F9F9F9'
    },
    rightBox: {
        height: '100%',
        width: 70,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
    },
    rightText: {
        fontSize: 14,
        color: '#333333',
    },

    contractCountContainer: {
        height: 40,
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        alignItems: 'center',
    },

    contractCount: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginLeft: 15
    },

    chargeContainer: {
        width: 52,
        height: 27,
        backgroundColor: '#FEFCEB',
        borderRadius: 4,
        position: 'absolute',
        right: 15,
        alignItems: 'center',
        justifyContent: 'center',
    },

    chargeTitle: {
        fontWeight: '500',
        fontSize: 14,
        color: '#F96A0E'
    },

    searchContainer: {
        paddingTop: 10,
        // height: 40,
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        alignItems: 'center'
    },

    searchLayout: {
        width: screenW - 30,
        height: 34,
        backgroundColor: '#F7F8F8',
        borderRadius: 5,
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 15
    },

    sarchIcon: {
        width: 16,
        height: 16,
        marginLeft: 10,
        marginRight: 10
    },

    inputbox: {
        width: screenW - 40 - 30,
        height: 34,
        fontSize: 14,
        padding: 0,
        margin: 0,
    },
    sarchClose: {
        width: 15,
        height: 15,
    },

    chooseContainer: {
        height: 44,
        backgroundColor: '#ffffff',
        flexDirection: 'row'
    },

    choosePer: {
        width: '33.33%',
        height: 45,
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row'
    },

    choosePerinner: {
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row'
    },

    choosetype: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333'
    },

    choosetypeSelect: {
        fontWeight: '400',
        fontSize: 14,
        color: '#F96A0E'
    },

    choosearrow: {
        width: 15,
        height: 15,

    },

    choosesign: {
        width: 18,
        height: 18,
        marginRight: 3
    },

    itemcontainer: {
        backgroundColor: '#ffffff',
        marginTop: 10,
    },

    itemtop: {
        height: 44,
        paddingLeft: 15,
        paddingRight: 15,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 0.5,
        width:'100%'
    },

    contractNameTitle: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333'
    },

    contractName: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginLeft: 3,
        flex:1,
        marginRight:5
    },

    contractStatus: {
        fontWeight: '400',
        fontSize: 14,
        color: '#ED542E',
        
    },
    contractStatusComplete: {
        fontWeight: '400',
        fontSize: 14,
        color: '#2CE454',
        
    },

    contractModel: {
        marginTop: 12,
        fontWeight: '500',
        fontSize: 14,
        color: '#333333',
        marginLeft: 15
    },

    commonbuttwen: {
        marginLeft: 15,
        marginTop: 10,
        flexDirection: 'row'
    },

    commonTitle: {
        fontWeight: '400',
        fontSize: 14,
        color: '#999999',
    },

    commonValue: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginLeft: 5
    },

    contractCarContainer: {
        backgroundColor: '#F4F4F4',
        marginLeft: 12,
        marginRight: 12,
        marginTop: 12,
        borderRadius: 8,
        height: 76,
        flexDirection: 'row',
        alignItems: 'center'
    },

    contractcar: {
        width: 52,
        height: 52,
        marginLeft: 12,
        borderRadius: 2,
        resizeMode: 'contain'
    },

    contractCarTitle: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginLeft: 8,
        marginRight: 15,
        width: screenW - 100,
    },

    contractCarVin: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginTop: 12,
        marginLeft: 8
    },

    itemBottomContainer: {
        height: 55,
        alignItems: 'center',
        flexDirection: 'row',
        justifyContent: 'flex-end'
    },

    itemBottomLayout: {
        flexDirection: 'row',
        justifyContent: 'flex-end'
    },

    commonbtn: {
        borderRadius: 18,
        paddingLeft: 10,
        paddingRight: 10,
        paddingTop: 5,
        paddingBottom: 5,
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: 12,
        borderColor: '#e1e1e1',
        borderWidth: 0.5,

    },

    commonBtnTitle: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
    },


    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

    addcontractContainer: {
        width: 128,
        height: 48,
        borderRadius: 99,
        position: 'absolute',
        backgroundColor: '#FFEF3A',
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row'
    },

    contractadd: {
        marginRight: 6,
        width: 30,
        height: 30
    },

    addcontractTitle: {
        fontWeight: '500',
        fontSize: 16,
        color: '#333333',
    },

    chooseTypeContaner: {
        width: screenW,
        height: screenH,
        backgroundColor: 'rgba(0, 0, 0, 0.4)',
        zIndex: 1000,
        position: "absolute",
        left: 0,
        bottom: 0,
        justifyContent: "center",
        alignItems: "center",
    },

    chooseTypeBottoms: {
        width: screenW,
        backgroundColor: '#f9f9f9',
        position: 'absolute',
        height: 230,
        bottom: 0
    },

    chooseTypeTop: {
        alignItems: 'center',
        flexDirection: 'row',
        height: 45,
        width: screenW,
        justifyContent: 'center'
    },

    choosetypetitle: {
        fontWeight: '500',
        fontSize: 18,
        color: '#333333',
    },

    chooseclose: {

        right: 15,
        position: 'absolute'
    },

    chooseCenterContainer: {
        height: 135,
        borderRadius: 5,
        marginLeft: 15,
        marginRight: 15,
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        alignItems: 'center'
    },

    funcontainer: {
        width: (screenW - 30 - 32) / 3,
        height: 100,
        backgroundColor: '#F2F7FE',
        borderRadius: 8,
        marginLeft: 8,
        alignItems: 'center',
        justifyContent: 'center'
    },

    contractTypeIcon: {
        width: 45,
        height: 45
    },

    cobtractTypeTitle: {
        fontWeight: '500',
        fontSize: 12,
        color: '#000000',
        marginTop: 8
    },

    rescissionContainer: {
        height: 40,
        backgroundColor: '#e1e1e1',
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 30,
        marginRight: 30,
        marginTop: 15
    },



    rescissionTypeContaner: {
        width: screenW,
        backgroundColor: '#f9f9f9',
        position: 'absolute',
        height: 280
    },


    containerAssign: {
        width: screenW,
        height: screenH,
        backgroundColor: 'rgba(0, 0, 0, 0.4)',
        zIndex: 1000,
        position: "absolute",
        left: 0,
        bottom: 0,
    },

    closeContainer: {
        flex: 1
    },

    modalContainer: {

        width: screenW,
        backgroundColor: '#ffffff',
        position: 'absolute',
        bottom: 0
    },

    choosemodalContainer: {
        width: screenW,
        backgroundColor: '#ffffff',
        position: 'absolute',
        bottom: 0,
        maxHeight: 500
    },

    assignItem: {
        height: 45,
        alignItems: 'center',
        justifyContent: 'center',
        width: screenW,
    },

    itemText: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
    },

    itemTextConfirm: {
        fontWeight: '400',
        fontSize: 14,
        color: 'blue',
    },


    borderBottom: {
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 0.5,
        position: 'absolute',
        bottom: 0,
        width: screenW,
        marginLeft: 15
    },

    assignChecked: {
        position: 'absolute',
        right: 15,
        width: 18,
        height: 18,
    },

    commondialog: {
        width: screenW - 30,
        backgroundColor: '#ffffff',
        borderRadius: 4,
        alignItems: 'center'
    }




})